package com.example.demo.service.impl;

import com.example.demo.dto.RegisterDTO;
import com.example.demo.exception.UserAlreadyExistsException;
import com.example.demo.mapper.UserMapper;
import com.example.demo.model.*;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.example.demo.model.UserRole;
import com.example.demo.service.AuthService;
import org.springframework.security.authentication.BadCredentialsException;


import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;
import javax.validation.Valid;



@Service
public class AuthServiceImpl implements AuthService {

    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;

    // 构造函数注入依赖
    public AuthServiceImpl(UserMapper userMapper, PasswordEncoder passwordEncoder) {
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    @Transactional
    public User registerUser(@Valid RegisterDTO registerDTO) throws UserAlreadyExistsException {
        // 1. 检查用户名是否已存在
        if (userMapper.existsByUsername(registerDTO.getUsername())) {
            throw new UserAlreadyExistsException("用户名已被占用: " + registerDTO.getUsername());
        }

        // 2. 构建用户实体（自动生成 userId）
        User user = User.builder()
                .username(registerDTO.getUsername())
                .password(passwordEncoder.encode(registerDTO.getPassword())) // 密码加密
                .role(registerDTO.getRole() != null ? registerDTO.getRole() : UserRole.USER) // 默认角色
                .build();


        // 3. 执行插入操作
        int affectedRows = userMapper.insert(user);
        if (affectedRows != 1) {
            throw new RuntimeException("用户创建失败");
        }
        return user;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 查询用户
        User user = userMapper.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }

        // 2. 转换为 Spring Security 的 UserDetails
        return org.springframework.security.core.userdetails.User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .roles(user.getRole().name()) // 角色需以 ROLE_ 前缀存储
                .build();
    }

    @Override
    public UserDetails authenticateUser(String username, String password) {
        // 1. 加载用户
        UserDetails userDetails = loadUserByUsername(username);

        // 2. 验证密码
        if (!passwordEncoder.matches(password, userDetails.getPassword())) {
            throw new BadCredentialsException("密码验证失败");
        }

        return userDetails;
    }
}